package driver.services;


import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import driver.util.NotificationUtils;
import driver.util.Util;

public class FcmMessageService extends FirebaseMessagingService {

    private SharedPreferences mFlashSharedPreferences;
    private String mFlashSharePreferenceName = "Flash";

    @Override
    public void onCreate() {
        super.onCreate();
        Util.debugApp('d', "接收消息的服务已开启");
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
    }

    /**
     * 获取注册令牌token。
     * <p>
     * 注册令牌可能会在发生下列情况时更改：
     * <p>
     * 1、应用在新设备上恢复
     * <p>
     * 2、用户卸载/重新安装应用
     * <p>
     * 3、用户清除应用数据。
     *
     * @param token
     */
    @Override
    public void onNewToken(@NonNull String token) {
        super.onNewToken(token);
        Util.debugApp('d', "Refreshed token: " + token);
        if (mFlashSharedPreferences != null) {
            SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
            editor.putString("googleToken", token);
            editor.commit();
            Util.debugApp('d', "开始保存google token " + token);
        }
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Util.debugApp('d', "onMessageReceived: " + remoteMessage);
        Util.debugApp('d', "APP处于前台消息标题" + remoteMessage.getNotification().getTitle());
        Util.debugApp('d', "APP处于前台消息内容" + remoteMessage.getNotification().getBody());
        Util.debugApp('d', "Data消息（为空）" + remoteMessage.getData());
        Util.debugApp('d', "服务器" + remoteMessage.getFrom());

        if (remoteMessage.getNotification() != null && remoteMessage.getNotification().getBody() != null) {
            String title = remoteMessage.getNotification().getTitle();
            String content = remoteMessage.getNotification().getBody();
            Handler handlerThree = new Handler(Looper.getMainLooper());
            handlerThree.post(new Runnable() {
                public void run() {
                    NotificationUtils notificationUtils = new NotificationUtils(FcmMessageService.this);
                    notificationUtils.sendNotification(title, content);
                }
            });
        }
    }


    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
        Util.debugApp('d', "onDeletedMessages");
    }

    @Override
    public void onMessageSent(String s) {
        super.onMessageSent(s);
        Util.debugApp('d', "onMessageSent " + s);
    }

    @Override
    public void onSendError(String s, Exception e) {
        super.onSendError(s, e);
        Util.debugApp('d', "onSendError " + s);
    }
}